package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.MoveOnShelfTaskDetailAdapter;
import com.mflex.mwms.adapter.TransferOnDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.MoveOnPdaRequest;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MoveOnShelfOnTaskDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_ShelfLocation)
    EditText stvShelfLocation;

    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

//    @BindView(R.id.button_clear)
//    Button buttonClear;
//
//    @BindView(R.id.button_save)
//    Button buttonSave;

    @BindView(R.id.lvTaskDetailList)
    ListView lvTaskDetailList;

    MiniLoadingDialog mMiniLoadingDialog;

    List<TaskDetail> taskDetailList;

    private String taskNo;
    private String boxNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_move_on_shelf_on_task_detail);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        Intent intent = getIntent();
        Type listType = new TypeToken<ArrayList<TaskDetail>>() {
        }.getType();
        taskDetailList = (List<TaskDetail>) JsonUtil.fromJson(intent.getStringExtra("taskDetail"), listType);
        taskNo = intent.getStringExtra("taskNo");
        boxNumber = intent.getStringExtra("boxNumber");

//        MoveOnShelfTaskDetailAdapter moveOnShelfTaskDetailAdapter = new MoveOnShelfTaskDetailAdapter(this, taskDetailList);
//        lvTaskDetailList.setAdapter(moveOnShelfTaskDetailAdapter);

        stvTaskNo.setFocusable(false);
        stvTaskNo.setText(taskNo);

        stvBoxNumber.setOnKeyListener(this);
        stvShelfLocation.setOnKeyListener(this);
//        buttonClear.setOnClickListener(this);
//        buttonSave.setOnClickListener(this);

        requestTask(this.getCurrentFocus());

        stvShelfLocation.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                stvShelfLocation.setText("");
                return false;
            }
        });
        stvShelfLocation.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvShelfLocation.requestFocus();
            }
        }, 200);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.button_clear:
//                clearButtonMd(view);
//                break;
//            case R.id.button_save:
//                saveButtonMd(view);
//                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNumber:
                    CheckBoxNumber(view);
                    break;
                case R.id.stv_ShelfLocation:
                    cheShelfLocation(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void CheckBoxNumber(View view) {
        if (StringUtils.isEmpty(stvShelfLocation.getText().toString())) {
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("入库库位未输入")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(MoveOnShelfOnTaskDetailActivity.this, "入库库位未输入");
            return;
        }


        boolean flag = false;
        boolean existFlag = false;

        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName()) && taskDetail.checked) {
                existFlag = true;
                break;
            }
        }
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
                flag = true;
                break;
            }
        }


        if (!flag) {
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号不在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(MoveOnShelfOnTaskDetailActivity.this, "箱号不在列表中");
            return;
        }
        if (existFlag) {
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号已在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(MoveOnShelfOnTaskDetailActivity.this, "箱号已在列表中");
            return;
        }
//        stvBoxNumber.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                stvBoxNumber.requestFocus();
//            }
//        }, 200);


        MoveOnPdaRequest moveOnPdaRequest = new MoveOnPdaRequest();
        moveOnPdaRequest.setTaskNo(taskNo);
        moveOnPdaRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
        moveOnPdaRequest.setShelfLocation(stvShelfLocation.getText().toString());
        moveOnPdaRequest.setBoxNumber(stvBoxNumber.getText().toString());

        mMiniLoadingDialog.show();
        XHttp.post("api/ShelfOn/TaskMoveOnPda")
                .upJson(JsonUtil.toJson(moveOnPdaRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        int count = 0;
                        for (TaskDetail detail : taskDetailList) {
                            if (detail.isChecked()) {
                                count++;
                            }
                        }
                        if ((count + 1) == taskDetailList.size()) {
                            //结束移库任务
                            XToastUtils.success("移库任务已完成", 3500);
                            setResult(0);
                            finish();
                        } else {
                            for (TaskDetail detail : taskDetailList) {
                                if (StringUtils.equals(stvBoxNumber.getText().toString(), detail.getDetailName())) {
                                    detail.setChecked(true);
                                }
                            }

                            Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
                                @Override
                                public int compare(TaskDetail t0, TaskDetail t1) {
                                    if (!t0.isChecked() && t1.isChecked()) {
                                        return -1;
                                    }
                                    return 0;
                                }
                            });

                            XToastUtils.success("移库成功", 2000);
                            MoveOnShelfTaskDetailAdapter moveOnShelfTaskDetailAdapter = new MoveOnShelfTaskDetailAdapter(MoveOnShelfOnTaskDetailActivity.this, taskDetailList);
                            lvTaskDetailList.setAdapter(moveOnShelfTaskDetailAdapter);
                            stvBoxNumber.setText("");
//                            stvShelfLocation.setText("");
                            stvBoxNumber.requestFocus();
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(MoveOnShelfOnTaskDetailActivity.this, e);
                        stvShelfLocation.setText("");
                        stvShelfLocation.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvShelfLocation.requestFocus();
                            }
                        }, 200);
                    }
                }) {
                });
    }

    /**
     * 入库库位检查
     *
     * @param view
     */
    private void saveButtonMd(View view) {

    }

    private void clearButtonMd(View v) {
        stvBoxNumber.setText("");
        stvShelfLocation.setText("");
        stvShelfLocation.requestFocus();
        taskDetailList = new ArrayList<>();
        TransferOnDetailAdapter transferOnDetailAdapter = new TransferOnDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(transferOnDetailAdapter);
    }

    private void cheShelfLocation(View v) {
        mMiniLoadingDialog.show();
        XHttp.get("api/ShelfOn/CheckShelfOnLocation")
                .params("Location", stvShelfLocation.getText().toString())
                .params("Warehouse", MMKVUtils.getString("Warehose", ""))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvShelfLocation.setText("");
                        stvShelfLocation.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(MoveOnShelfOnTaskDetailActivity.this, e);
                    }
                }) {
                });

    }

    private void requestTask(View v) {
        mMiniLoadingDialog.show();
        XHttp.get("api/Task/GetMoveTaskListForPda")
                .params("BoxNumber", boxNumber)
                .params("TaskNo", taskNo)
                .params("CurrentWarehouse", MMKVUtils.getString("Warehose", ""))
                .params("TaskStatusName", 0)
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<List<Task>>, List<Task>>(new SimpleCallBack<List<Task>>() {

                    @Override
                    public void onSuccess(List<Task> response) {
                        mMiniLoadingDialog.dismiss();
                        taskDetailList = response.get(0).getTaskDetails();

                        Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
                            @Override
                            public int compare(TaskDetail t0, TaskDetail t1) {
                                if (StringUtils.isEmpty(t0.RecommendLoc) && StringUtils.isEmpty(t1.RecommendLoc)) {
                                    return -1;
                                } else if (!StringUtils.isEmpty(t0.RecommendLoc) && StringUtils.isEmpty(t1.RecommendLoc)) {
                                    return -1;
                                } else if (StringUtils.isEmpty(t0.RecommendLoc) && !StringUtils.isEmpty(t1.RecommendLoc)) {
                                    return 1;
                                } else if (!StringUtils.isEmpty(t0.RecommendLoc) && !StringUtils.isEmpty(t1.RecommendLoc)) {
                                    if (t0.RecommendLoc.compareTo(t1.RecommendLoc) > 0) {
                                        return 1;
                                    } else if (t0.RecommendLoc.compareTo(t1.RecommendLoc) == 0) {
                                        return 0;
                                    } else {
                                        return -1;
                                    }
                                } else {
                                    return 0;
                                }
                            }
                        });

                        MoveOnShelfTaskDetailAdapter moveOnShelfTaskDetailAdapter = new MoveOnShelfTaskDetailAdapter(MoveOnShelfOnTaskDetailActivity.this, taskDetailList);
                        lvTaskDetailList.setAdapter(moveOnShelfTaskDetailAdapter);

//                        if (StringUtils.isEmpty(boxNumber)) {
//                            stvBoxNumber.setText("");
//                            stvBoxNumber.requestFocus();
//                        } else {
//                            stvBoxNumber.setText(boxNumber);
//                            stvShelfLocation.requestFocus();
//                        }

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.setText("");
                        stvBoxNumber.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(MoveOnShelfOnTaskDetailActivity.this, e);
                    }
                }) {
                });
    }
}